//
//  MQOAuthViewController.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/1/17.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

var WB_APPKEY = "1107592889"
var WB_APPSECRET = "e8023d98846d6ce7b9a265346e9bdc2c"
var WB_REDIRECT_URI = "http://www.itheima.com/"

//redirect_uri

class MQOAuthViewController: UIViewController, UIWebViewDelegate {
    override func loadView() {
        view = webView
        setupUI()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    // MARK: - 懒加载
    lazy var webView:UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
// MARK: - 初始化navigationItem
    private func setupUI(){
        navigationItem.title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "close")
    }

    @objc private func autoFill(){
        let jsString = "document.getElementById('userId').value='vgfjh15964@163.com';document.getElementById('passwd').value='qw1987';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    @objc private func close(){
        SVProgressHUD.dismiss()
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }

}


// MARK: -  UIWebViewDelegate
extension MQOAuthViewController{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        printfLog(request.URL?.absoluteString)
        guard let urlString = request.URL?.absoluteString else{
            return true
        }
        
        if !urlString.hasPrefix(WB_REDIRECT_URI){
            return true
        }
        
        if let query = request.URL?.query where query.hasPrefix("code="){
            printfLog(query)
//            (query as NSString).substringFromIndex(5)
            let code = query.substringFromIndex("code=".endIndex)
            
            MQUserAccountViewModel.shareUserAccountViewModel.loadAccessToken(code, complete: { (isSuccess) -> () in
                if isSuccess{
                    //切换控制器
                    printfLog("登录成功,切换控制器")
                    SVProgressHUD.dismiss()
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(MQSwitchRootViewControllerNotification, object: self)
                    })
                }else{
                    printfLog("请求用户数据失败")
                }
            })
        

        }else{
            close()
        }
        
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
